<?php

namespace App\Http\Controllers\Pay;

use App\Http\Controllers\Controller;
use App\Imports\Pay\YanglaoImport;
use App\Imports\Personnel\ImportAdmin;
use App\Models\Pay\Gongjijin;
use App\Models\Pay\Gongling;
use App\Models\Pay\Gongshang;
use App\Models\Pay\Shiye;
use App\Models\Pay\Yanglao;
use App\Models\Pay\Yiliao;
use App\Models\Personnel\Personnel;
use App\Models\Personnel\PersonnelEduExperience;
use App\Models\Personnel\PersonnelFamily;
use App\Models\Personnel\PersonnelFile;
use App\Models\Personnel\PersonnelPay;
use App\Models\Personnel\PersonnelWorkExperience;
use App\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Appstract\Options\Option;

class PayController extends Controller
{
    /**
     * 人员列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function adminRecordList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getAdminRecordList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getAdminRecordList($countParams)->count();

        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    /**
     * 养老列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function yanglaoList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getYanglaoList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getYanglaoList($countParams)->count();

        return response()->formatJson(['yanglaoData' => $data, 'count' => $dataCount]);
    }

    public function getYanglaoList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Yanglao::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 数据转化
     *
     * @param  array  $data
     *
     * @return array
     */
    public function transYanglaoData(array $data): array
    {
        foreach ($data as $key => $row) {
            $data[$key]['date'] = date('Y-m', strtotime($row['date']));
            $data[$key]['name'] = $row['personnel']['name'];
            $data[$key]['type'] = $row['personnel']['type'] === 1 ? '驾驶员' : '行政人员';
        }

        return $data;
    }

    /**
     * 养老列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function yiliaoList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getYiliaoList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getYiliaoList($countParams)->count();

        return response()->formatJson(['yiliaoData' => $data, 'count' => $dataCount]);
    }

    public function getYiliaoList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Yiliao::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 养老列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function gongjijinList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getGongjijinList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getGongjijinList($countParams)->count();

        return response()->formatJson(['gongjijinData' => $data, 'count' => $dataCount]);
    }

    public function getGongjijinList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Gongjijin::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 失业列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function shiyeList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getShiyeList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getShiyeList($countParams)->count();

        return response()->formatJson(['shiyeData' => $data, 'count' => $dataCount]);
    }

    public function getShiyeList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Shiye::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 工伤列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function gongshangList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getGongshangList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getGongshangList($countParams)->count();

        return response()->formatJson(['gongshangData' => $data, 'count' => $dataCount]);
    }

    public function getGongshangList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Gongshang::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 工伤列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function gonglingList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getGonglingList($params)->orderByDesc('created_at')->get()->toArray();
        if ($data) {
            $data = $this->transYanglaoData($data);
        }
        $dataCount = $this->getGonglingList($countParams)->count();

        return response()->formatJson(['gonglingData' => $data, 'count' => $dataCount]);
    }

    public function getGonglingList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Gongling::query()->with('personnel:id,name,type');

        if (isset($params['date'])) {
            $query->where('date', date('Y-m-01', strtotime($params['date'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    public function getAdminRecordList($params)
    {
        $query = Personnel::query()->select('id', 'type', 'name')->with([
            'pay' => function ($query) use ($params) {
                if ($params['date']) {
                    $query->where('date', $params['date'].'-01');
                }
            },
        ])->where('type', 0);

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 人员列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function driverRecordList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);
        $data = $this->getDriverRecordList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getDriverRecordList($countParams)->count();

        return response()->formatJson(['personnel' => $data, 'count' => $dataCount]);
    }

    public function getDriverRecordList($params)
    {
        $query = Personnel::query()->select('id', 'type', 'name')->with([
            'pay' => function ($query) use ($params) {
                if ($params['date']) {
                    $query->where('date', $params['date'].'-01');
                }
            },
        ])->where('type', 1);

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 数据转化
     *
     * @param  array  $data
     *
     * @return array
     */
    public function transData(array $data): array
    {
        foreach ($data as $key => $personnel) {
            foreach ($personnel as $filed => $value) {
                if ($filed === 'pay') {
                    if ($value) {
                        foreach ($value as $v) {
                            $data[$key][$v['type']] = $v['amount'];
                            $data[$key]['date'] = $v['date'];
                        }
                    }
                    unset($data[$key][$filed]);
                }
            }
        }

        return $data;
    }

    /**
     * 获取车辆数据到编辑表单页面
     *
     * @param $id
     *
     * @return mixed
     */
    public function edit($id)
    {
        $personnel = Personnel::with('adminInfo')
            ->with('driverInfo')
            ->with('eduExperience')
            ->with('workExperience')
            ->with('family')
            ->with('file')
            ->with('pay')
            ->find($id)
            ->toArray();
        if (array_key_exists('admin_info', $personnel)) {
            $personnel['department_id'] = $personnel['admin_info']['department_id'];
            $personnel['office_id'] = $personnel['admin_info']['office_id'];
            $personnel['work_phone'] = $personnel['admin_info']['work_phone'];
            $personnel['is_join_tu'] = $personnel['driver_info']['is_join_tu'];
            $personnel['short_number'] = $personnel['admin_info']['short_number'];
        }
        if (array_key_exists('driver_info', $personnel)) {
            $personnel['team_num'] = $personnel['driver_info']['team_num'];
            $personnel['line_num'] = $personnel['driver_info']['line_num'];
            $personnel['is_join_tu'] = $personnel['driver_info']['is_join_tu'];
            $personnel['is_injured'] = $personnel['driver_info']['is_injured'];
            $personnel['bank_card_number'] = $personnel['driver_info']['bank_card_number'];
            $personnel['bank'] = $personnel['driver_info']['bank'];
            $personnel['injured_status'] = $personnel['driver_info']['injured_status'];
            $personnel['date'] = $personnel['driver_info']['date'];
            $personnel['place'] = $personnel['driver_info']['place'];
            $personnel['reason'] = $personnel['driver_info']['reason'];
            $personnel['description'] = $personnel['driver_info']['description'];
            $personnel['injured_photo_url'] = $personnel['driver_info']['injured_photo_url'];
        }
        $edus = [];
        if ($personnel['edu_experience']) {
            foreach ($personnel['edu_experience'] as $k => $v) {
                $v['index'] = $k + 1;
                $v['status'] = 1;
                $edus[] = $v;
            }
        }
        $personnel['edus'] = $edus;

        $works = [];
        if ($personnel['work_experience']) {
            foreach ($personnel['work_experience'] as $k => $v) {
                $v['index'] = $k + 1;
                $v['status'] = 1;
                $works[] = $v;
            }
        }
        $personnel['works'] = $works;

        $family = [];
        if ($personnel['family']) {
            foreach ($personnel['family'] as $k => $v) {
                $v['index'] = $k + 1;
                $v['status'] = 1;
                $family[] = $v;
            }
        }
        $personnel['family'] = $family;

        unset($personnel['edu_experience'], $personnel['work_experience'], $personnel['admin_info'], $personnel['driver_info']);

        $users = User::all();
        if (optional($personnel['file'])) {
            foreach ($personnel['file'] as $k => $file) {
                $personnel['file'][$k]['user_name'] = $users->where('id', $file['user_id'])->first()->name;
            }
        }

        $payData = [];
        if ($personnel['pay']) {
            $pay = collect($personnel['pay'])->groupBy('date')->toArray();
            foreach ($pay as $date => $item) {
                $month = [];
                $month['date'] = $date;
                foreach ($item as $k => $v) {
                    $month[$v['type']] = (float) $v['amount'];
                }
                $payData[] = $month;
            }
        }
        $personnel['pay'] = $payData;

        return response()->formatJson($personnel);
    }

    /**
     * 修改文章
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();

        $personnel = Personnel::query()->find($id);

        $result = $personnel->update($params);
        $message = $result ? '修改成功' : '修改失败';

        if ($params['type'] === 0) {
            $adminInfo = [
                'department_id' => $params['department_id'],
                'office_id'     => $params['office_id'],
                'is_join_tu'    => $params['is_join_tu'],
                'work_phone'    => $params['work_phone'],
                'short_number'  => $params['short_number'],
            ];
            $personnel->adminInfo()->updateOrCreate(
                ['personnel_id' => $id],
                $adminInfo
            );
        } else {
            $driverInfo = [
                'team_num'          => $params['team_num'],
                'line_num'          => $params['line_num'],
                'is_join_tu'        => $params['is_join_tu'],
                'is_injured'        => $params['is_injured'],
                'bank_card_number'  => $params['bank_card_number'],
                'bank'              => $params['bank'],
                'injured_status'    => $params['injured_status'],
                'date'              => $params['date'],
                'place'             => $params['place'],
                'reason'            => $params['reason'],
                'description'       => $params['description'],
                'injured_photo_url' => $params['injured_photo_url'],
            ];
            $personnel->driverInfo()->updateOrCreate(
                ['personnel_id' => $id],
                $driverInfo
            );
        }

        // 关联工作经历
        if (! empty($params['works'])) {
            foreach ($params['works'] as $work) {
                if (! array_key_exists('id', $work)) {
                    if ($work['status'] === 1) {
                        $workExperience = new PersonnelWorkExperience($work);
                        $personnel->workExperience()->save($workExperience);
                    }
                } else {
                    $workExperience = PersonnelWorkExperience::query()->find($work['id']);
                    $workExperience->update($work);
                }
            }
        }

        // 关联教育经历
        if (! empty($params['edus'])) {
            foreach ($params['edus'] as $k => $edu) {
                if (! array_key_exists('id', $edu)) {
                    if ($edu['status'] === 1) {
                        $eduExperience = new PersonnelEduExperience($edu);
                        $personnel->eduExperience()->save($eduExperience);
                    }
                } else {
                    $workExperience = PersonnelEduExperience::query()->find($edu['id']);
                    $workExperience->update($edu);
                }
            }
        }

        // 关联家庭成员
        if (! empty($params['family'])) {
            foreach ($params['family'] as $k => $person) {
                if (! array_key_exists('id', $person)) {
                    if ($person['status'] === 1) {
                        $family = new PersonnelFamily($person);
                        $personnel->family()->save($family);
                    }
                } else {
                    $workExperience = PersonnelFamily::query()->find($person['id']);
                    $workExperience->update($person);
                }
            }
        }

        // 关联资质文件
        if (! empty($params['adminFile'])) {
            foreach ($params['adminFile'] as $k => $work) {
                if (! array_key_exists('type', $work)) {
                    $work['type'] = 'admin';
                    $file = new PersonnelFile($work);
                    $personnel->file()->save($file);
                }
            }
        }

        // 关联工资详情
        if (! empty($params['pay'])) {
            $personnel->pay()->delete();
            foreach ($params['pay'] as $k => $pay) {
                foreach ($pay as $key => $v) {
                    if ($key !== 'date') {
                        $month = [];
                        $month['date'] = $pay['date'];
                        $month['type'] = $key;
                        $month['amount'] = $v;
                        $pay = new PersonnelPay($month);
                        $personnel->pay()->save($pay);
                    }
                }
            }
        }

        return response()->formatJson($result, $message);
    }

    /**
     * 删除人员
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $delCount = Personnel::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     *  导入养老数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importYl(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 11);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'self_number',
            'name',
            'personal_base',
            'unit_payment',
            'personal_payment',
            'total_payment',
            'remarks',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->yanglao()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入医疗数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importYiliao(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 11);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'self_number',
            'name',
            'personal_base',
            'unit_payment',
            'personal_payment',
            'total_payment',
            'remarks',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->yiliao()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入失业数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importShiye(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 11);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'self_number',
            'name',
            'personal_base',
            'unit_payment',
            'personal_payment',
            'total_payment',
            'remarks',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->shiye()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入工伤数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importGongshang(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 11);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'name',
            'personal_base',
            'proportion',
            'personal_payment',
            'remarks',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->gongshang()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入工龄数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importGongling(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $month = substr($allData[0][0][2], 0, 2);
        $date = '2020-'.sprintf('%02d', $month).'-01';

        $fields = [
            'line',
            'name',
            'salary',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', 1)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->gongling()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入公积金数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importGongjijin(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new YanglaoImport(), public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 11);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'self_number',
            'name',
            'personal_base',
            'unit_payment',
            'personal_payment',
            'total_payment',
            'remarks',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                if ($row[0] === null) {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $item['personnel_id'] = $personnelObj->id;
                    $item['date'] = $date;
                    unset($item['index'], $item['name']);
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->gongjijin()->updateOrCreate($item);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入失业数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importSy(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new ImportAdmin, public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 12);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'code',
            'name',
            'base',
            'unit_pay',
            'personal_pay',
            'total_pay',
            'note',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->pay()->updateOrCreate([
                        'date'         => $date,
                        'type'         => 'unemployment_insurance',
                        'amount'       => $item['personal_pay'],
                        'personnel_id' => $personnelObj->id,
                    ]);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入工伤数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importGs(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new ImportAdmin, public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 12);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $fields = [
            'index',
            'name',
            'base',
            'rate',
            'personal_pay',
            'note',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                if ($row[0] === '合计') {
                    break;
                }
                $item = [];
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $personnel = Personnel::query()->find($personnelObj->id);
                    $personnel->pay()->updateOrCreate([
                        'date'         => $date,
                        'type'         => 'injury_insurance',
                        'amount'       => $item['base'] * $item['rate'],
                        'personnel_id' => $personnelObj->id,
                    ]);
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    /**
     *  导入养老数据
     *
     * @param  Request  $request
     *
     * @return mixed
     * @throws Exception
     */
    public function importOther(Request $request)
    {
        $urlParse = parse_url($request->input('url'));
        $allData = Excel::toArray(new ImportAdmin, public_path().$urlParse['path']);

        $dateStr = substr($allData[0][0][0], 0, 12);
        $dateArr = date_parse_from_format('Y-m-d', $dateStr);
        $date = $dateArr['year'].'-'.sprintf('%02d', $dateArr['month']).'-01';

        $adminFields = [
            'index',
            'name',
            'base_pay',
            'job_pay',
            'performance_pay',
            'car_allowance',
            'seniority_pay',
            'cool_fee',
            'overtime_pay',
            'difference_pay',
            'leave_deductions',
            'late_deductions',
            'clothes_cost',
            'accumulation_fund',
            'tu_membership_dues',
        ];
        $driverFields = [
            'index',
            'name',
            'base_pay',
            'fix_car_allowance',
            'seniority_pay',
            'sell_card_rewards',
            'overtime_pay',
            'bicycle_accounting',
            'cool_fee',
            'tu_membership_dues',
        ];
        $allPersonnel = Personnel::query()->get();
        // 整理数据，填充合并的单元格数据
        foreach ($allData as $key => $fullData) {
            array_shift($fullData);
            array_shift($fullData);
            foreach ($fullData as $row) {
                $item = [];
                $fields = $key === 0 ? $adminFields : $driverFields;
                foreach ($fields as $index => $field) {
                    $item[$field] = $row[$index];
                }

                $item['name'] = Str::of($item['name'])->trim()->replace(' ', '');

                $personnelObj = $allPersonnel->where('type', $key)->where('name', $item['name'])->first();
                if ($personnelObj) {
                    $personnel = Personnel::query()->find($personnelObj->id);
                    unset($item['id'], $item['name']);
                    foreach ($item as $f => $amount) {
                        $personnel->pay()->updateOrCreate([
                            'date'         => $date,
                            'type'         => $f,
                            'amount'       => $amount ?? 0,
                            'personnel_id' => $personnelObj->id,
                        ]);
                    }
                }
            }
        }

        return response()->formatJson(true, '导入成功');
    }

    public function getPaySettings()
    {
        $options = Option::all()->toArray();
        $settings = [];
        if ($options) {
            foreach ($options as $k => $v) {
                $settings[$v['key']] = $v['value'];
            }
        }

        return response()->formatJson(['result' => $settings]);
    }

    public function saveSettings(Request $request)
    {
        $params = $request->all();
        \option($params);

        return response()->formatJson(true, '保存成功');
    }
}
